
#include "Tree.h"

#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include <vector>
#include <fstream>
#include <stdio.h>
#include <utility>
#include <stack>
#include <queue>
#include <set>

using namespace std;

Tree::Tree(string filename){
  string line;
  ifstream treefile;
 // void* line = new int[1];


  treefile.open(filename.c_str());
  if(!treefile.is_open()){
    printf("Error opening %s\n", filename.c_str());
  }
  numFeatures=0;
  numNodes=0;

  treefile >> numFeatures >>numNodes;
  printf("Tree for %d features, with %d nodes\n",numFeatures, numNodes);
  int readcounter=0;

  while(!treefile.eof() && readcounter<numNodes){
     TreeNode* node = new TreeNode;
     treefile >> node->number >> node->feature >> node->threshold >> node->childL >> node->childR >>node->p;
     //printf("New node : %d %d %f %d %d %f\n", node->number , node->feature, node->threshold,node->childL, node->childR,node->p);
     nodes.push_back(node);
     readcounter++;
  }
  treefile.close();

/*
  // test : print out a few nodes
  int i=0;
  printf("treenode #%d : %d %d %f %d %d %f\n",i, nodes[i]->number, nodes[i]->feature, nodes[i]->threshold, nodes[i]->childL, nodes[i]->childR, nodes[i]->p);
  i=34;
  printf("treenode #%d : %d %d %f %d %d %f\n",i, nodes[i]->number, nodes[i]->feature, nodes[i]->threshold, nodes[i]->childL, nodes[i]->childR, nodes[i]->p);
  i=numNodes-1;
  printf("treenode #%d : %d %d %f %d %d %f\n",i, nodes[i]->number, nodes[i]->feature, nodes[i]->threshold, nodes[i]->childL, nodes[i]->childR, nodes[i]->p);*/
}

void Tree::printTree(){
   printf("Tree with %d nodes, for data with %d features:\n",numNodes, numFeatures);
   for (int i=0; i<numNodes; i++){
        printf("treenode #%d : %d %d %f %d %d %f\n",i, nodes[i]->number, nodes[i]->feature, nodes[i]->threshold, nodes[i]->childL, nodes[i]->childR, nodes[i]->p);
   }
}

float Tree::getCost(Node* node){
    if (numFeatures != node->features){
       //cerr << "The node doesn't have the same number of features as the tree!\n";
       //return NULL;
    }
    int treenodenumber = 0;
    while(nodes[treenodenumber]->feature >= 0){
       //printf("Treenode #%d\n",treenodenumber);
//     if(node->costs[nodes[treenodenumber]->feature+22] > nodes[treenodenumber]->threshold){
       if(node->costs[nodes[treenodenumber]->feature+12] > nodes[treenodenumber]->threshold){ 
         treenodenumber = nodes[treenodenumber]->childL;
       }else{
          treenodenumber = nodes[treenodenumber]->childR;          
       }
    }
    float proba = nodes[treenodenumber]->p;
    //return -log(proba);
    return proba;
}

/*
int main(int argc, char** argv){
  printf("loading tree \n");
  Tree tree("./matlab/tree.txt");
  tree.printTree();
  return 1;
}
*/

